package it.tukano.check;

import java.io.PrintStream;

/**
 * Check utilities
 * @author pgi
 */
public class Checks {

    /**
     * Checks the type of a reference is compatible with a certain type
     * @param instance the value to check
     * @param type the type to check the value against
     */
    public static void InstanceOf(Object instance, Class<?> type) {
        if(instance == null) throw new CheckException("null is not <: " + type);
        if(!type.isAssignableFrom(instance.getClass())) throw new CheckException(instance + " of type " + instance.getClass() + " is not <: " + type);
    }

    public static void numericEquals(int value, int expected) {
        if(value != expected) throw new CheckException("Expected : " + expected + " found " + value);
    }

    public static void True(boolean v) {
        if(v == false) throw new CheckException("Expected true, was false");
    }

    public static void False(boolean v) {
        if(v == true) throw new CheckException("Expected false, was true");
    }

    private Checks() {}

    private static PrintStream out = System.out;

    private static void writeStackInfo() {
        Thread thread = Thread.currentThread();
        StackTraceElement[] trace = thread.getStackTrace();
        if(trace.length > 3) {
            out.println("CHECK FAILURE AT: " + trace[2]);
        }
    }

    /**
     * Check a reference for null value
     * @param reference the reference to check
     * @param message the message tokens to send if the reference is null
     * @throws CheckException
     */
    public static void NotNull(Object reference, String message) throws CheckException {
        if(reference == null) {
            writeStackInfo();
            throw new CheckException(message);
        }
    }

    /**
     * Checks that a reference is != null
     * @param reference the pointer to check
     * @throws CheckException if the check fails
     */
    public static void NotNull(Object reference) throws CheckException {
        NotNull(reference, "NotNull Check Failure");
    }
}
